<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    // 快照沙箱
    /* class SnapshotSandbox {
      constructor(){
        this.proxy = window;
        this.windowSnapshot = {}; // window对象快照
        this.modifyPropsMap = {}; // 记录修改的数据
        this.active();
      }
      // 激活
      active(){
        for(const prop in window){
          if(window.hasOwnProperty(prop)){
            this.windowSnapshot[prop] = window[prop]
          }
        }

        Object.keys(this.modifyPropsMap).forEach(p => {
          window[p] = this.modifyPropsMap[p]
        })
      }
      // 失活
      inactive(){
        for(const prop in window){
          if(window.hasOwnProperty(prop)){
            if(window[prop] !== this.windowSnapshot[prop]){
              this.modifyPropsMap[prop] = window[prop]
              window[prop] = this.windowSnapshot[prop]
            }
          }
        }
      }
    }

    let sandbox = new SnapshotSandbox()

    ;;((window) => {
      window.a = 1;
      window.b = 2
      console.log(window.a, window.b)
      sandbox.inactive()
      console.log(window.a, window.b)
      sandbox.active()
      console.log(window.a, window.b)
    })(sandbox.proxy); */

    // 多个子应用 es6 proxy
    class ProxySandbox {
      constructor(){
        const rawWindow = window
        const fakeWindow = {}
        const proxy = new Proxy(fakeWindow, {
          set(target, p, value){
            target[p] = value
            return true
          },
          get(target, p){
            return target[p] || rawWindow[p]
          }
        });
        this.proxy = proxy;
      }
    }

    let sandbox1 = new ProxySandbox();
    let sandbox2 = new ProxySandbox();

    window.a = 1;

    ;;((window) => {
      window.a = 'hello'
      console.log(window.a)
    })(sandbox1.proxy);

    ;;((window) => {
      window.a = 'world'
      console.log(window.a)
    })(sandbox2.proxy);
  </script>
</body>
</html>
